package bvethWin

import (
	"bveth"
	"github.com/lxn/walk"
	. "github.com/lxn/walk/declarative"

	// "os"
	// "strings"
	"time"

	"jk/jklog"
	// "strconv"
)

type bvethWindow struct {
	*walk.MainWindow
	model       *EnvModel
	refresh     *walk.PushButton
	listDevices *walk.ListBox
	sendRequest bool
	counts      int
}

func (bv *bvethWindow) setModelItemThread() {
	for {
		cnt := len(bveth.GlobalDeviceList.Device)
		if bv.counts != cnt {
			bv.counts = cnt
			bv.model.resetModelItem()

			bv.sendRequest = false
			bv.model.PublishItemsReset()
		}
		time.Sleep(500 * time.Millisecond)
	}
}

func (bv *bvethWindow) sendRequestRefresh() {
	if bv.sendRequest == true {
		return
	}
	for {
		if bv.sendRequest == false {
			break
		}
	}
	bveth.JKStartBroadCast()
	bv.sendRequest = true
}

func BvEthWindow(parent walk.Window) {
	mw := new(bvethWindow)

	bveth.JKStartBroadCast()

	mw.model = NewEnvModel()

	main := MainWindow{
		AssignTo: &mw.MainWindow,
		Title:    "局域网工具",
		MinSize:  Size{400, 320},
		Layout:   VBox{},
		Children: []Widget{
			ListBox{
				AssignTo:        &mw.listDevices,
				Model:           mw.model,
				OnItemActivated: mw.lb_ItemActivated,
				// ReadOnly: true,
			},
			PushButton{
				AssignTo:  &mw.refresh,
				Text:      "刷新",
				OnClicked: mw.sendRequestRefresh,
			},
		},
	}

	err := main.Create()
	if err != nil {
		jklog.L().Fatal(err)
	}

	go mw.setModelItemThread()

	mw.Run()
}

func (mw *bvethWindow) lb_ItemActivated() {
	i := mw.listDevices.CurrentIndex()
	bvethListWindowStart(mw, bveth.GlobalDeviceList.Device[i])
}

type EnvItem struct {
	name  string
	value string
}

type EnvModel struct {
	walk.ListModelBase
	items []EnvItem
}

func NewEnvModel() *EnvModel {
	// jklog.L().Infoln("get devices len ", len(bveth.GlobalDeviceList.Device))
	// m := &EnvModel{items: make([]EnvItem, len(bveth.GlobalDeviceList.Device))}
	var m EnvModel
	for _, t := range bveth.GlobalDeviceList.Device {
		// jklog.L().Infoln(t.Name, ":", t.MacAddr)
		ei := EnvItem{t.Name, t.MacAddr}
		m.items = append(m.items, ei)
	}

	return &m
}

func (m *EnvModel) resetModelItem() int {
	m.items = m.items[:0]
	for _, t := range bveth.GlobalDeviceList.Device {
		ei := EnvItem{t.Name, t.MacAddr}
		m.items = append(m.items, ei)
	}
	return len(m.items)
}

func (m *EnvModel) ItemCount() int {
	return len(m.items)
}

func (m *EnvModel) Value(index int) interface{} {
	return m.items[index].name
}
